package com.iqiyi.pps.epg.core.infrastructure.mail;

import com.iqiyi.kiwi.utils.StringUitl;
import com.iqiyi.pps.epg.core.model.common.MailHeader;
import com.iqiyi.pps.epg.core.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;

/**
 * 邮件服务
 * @auther hongbingfeng
 */
public abstract class MailService {
    private static Logger logger = LoggerFactory.getLogger(MailService.class);
    private String from;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    protected abstract JavaMailSender createMailSender();

    /**
     * 异步发送内容
     * @param header
     * @param content
     */
//    public void asyncSendMail(MailHeader header,String content)
//    {
//        EmailTask task = new EmailTask(header,content);
//        AsyncTaskFactory.getInstance().insertIntoDB(task, AsyncTask.POOL_TYPE_NOTICE, AsyncTask.Task_PRIORITY_1);
//    }

    /**
     * 异步发送内容
     * @param header
     * @param content
     */
//    public void asyncSendMail(MailHeader header,String content,String callbackId,String callbackType)
//    {
//        EmailTask task = new EmailTask(header,content,callbackId,callbackType);
//        AsyncTaskFactory.getInstance().insertIntoDB(task, AsyncTask.POOL_TYPE_NOTICE, AsyncTask.Task_PRIORITY_1);
//    }

    /**
     * 发送报警邮件
     */
//    public void sendErrorMail(String title,String content){
//        Boolean issend = Boolean.parseBoolean(Configuration.getString("mail.error.issend"));
//    	if(issend ==null || issend !=true){
//    		logger.info("此服务器不发送报警邮件，退出！");
//    		return;
//    	}
//        content = content.replaceAll("\r\n","<br/>");
//        MailHeader header = new MailHeader();
//        header.setTos(Configuration.getString("mail.error.contact").split(","));
//        header.setTitle(title);
//        asyncSendMail(header,content);
//    }

    public boolean sendMail(MailHeader header, Long templateId,String content) throws Exception {
        JavaMailSender mailSender = createMailSender();
        //mailSender.
        MimeMessage mailMessage = mailSender.createMimeMessage();
        //支持发送单人和多人,单人验证email地址
        String[] recipients = null;
        String code = "UTF-8";
        
        if(header.getTo()!=null){
            if(!StringUtil.validateEmail(header.getTo())){
                logger.error("[MailService] [sendMail] [validateEmail] [mail:{} is not a valid mail address!]",header.getTo());
                return false;
            }
            recipients = new String[] {header.getTo()};
        }else if(header.getTos()!=null){
            recipients = header.getTos();
        }else{
            logger.error("[MailService] [sendMail] [validateEmail] [header:{} not receivers!]",header);
            return false;
        }

        for(String recipient : recipients){
            if(recipient.indexOf("@tom") != -1){
                code = "GBK";
                break;
            }
        }
        //设置utf-8或GBK编码，否则邮件会有乱码
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, code);
        messageHelper.setTo(recipients);
        messageHelper.setFrom(from);//发送者
        messageHelper.setSubject(header.getTitle());//主题
        //邮件内容，注意加参数true，表示启用html格式
        content = StringUitl.removeContentTypeTag(content);
        messageHelper.setText(content, true);
        if(header.getAttachments()!=null){
            for(String filename:header.getAttachments()){
                File file = new File(filename);
                if(file.exists()){
                    messageHelper.addAttachment(file.getName(),file);
                }
            }
        }
        mailSender.send(mailMessage);
        return true;
    }

    public  static boolean testSendMail(MailHeader header, Long templateId,String content) throws MessagingException {
        JavaMailSenderImpl javaMail  =  new JavaMailSenderImpl();
        javaMail.setHost("smtp.mail.qiyi.com");
        javaMail.setPassword("Qiyi@vip123");
        javaMail.setUsername("vipservice");
        Properties prop  =  new Properties();
        prop.setProperty("mail.smtp.auth", "true");
        prop.setProperty("mail.smtp.timeout", "25000");
        javaMail.setJavaMailProperties(prop);

        MimeMessage message  =  javaMail.createMimeMessage();
        String code = "UTF-8";
        if(header.getTo().indexOf("@tom") != -1){
            code = "GBK";
        }

        MimeMessageHelper messageHelp  =  new MimeMessageHelper(message, true, code);
        messageHelp.setFrom("vipservice@qiyi.com");
        messageHelp.setTo(header.getTo());
        messageHelp.setSubject(header.getTitle());
        content = StringUitl.removeContentTypeTag(content);
        messageHelp.setText(content, true);
        javaMail.send(message);
        return true;
    }

    public static void main(String[] args) throws MessagingException {
        String content = "内容";

        content = StringUitl.removeContentTypeTag(content);
        MailHeader header = new MailHeader();
        header.setTo("sbydxk@tom.com");
        header.setTitle("标题2");
        testSendMail(header, 0l, content);
    }
}
